/*********************************************************
          File Name:weak_prt.cpp
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Tue 15 Sep 2015 07:22:08 PM CST
**********************************************************/

#include <iostream>
#include <string>
#include <memory>
#include <unistd.h>

// refer to http://stackoverflow.com/questions/12030650/when-is-stdweak-ptr-useful
// and
// http://stackoverflow.com/questions/4984381/shared-ptr-and-weak-ptr-differences

using std::shared_ptr;
using std::weak_ptr;
using std::string;

class TY;

class AC
{
        private:
                weak_ptr<TY> gf;
                //shared_ptr<TY> gf;      // cause memory leak
        public:
                void setgf(shared_ptr<TY> ty) 
                {
                        gf = ty;
                }
                
                bool over()
                {
                        return gf.expired();
                }
                
                AC() = default;
                ~AC() { std::cout << "abby say goodbye\n"; }
};

class TY
{
        private:
                shared_ptr<AC> bf;
        public:
                void setbf(shared_ptr<AC> abby)
                {
                        bf = abby;
                }
                TY() = default;
                ~TY() { std::cout << "taeyeon say goodbye\n"; }
};

int main()
{
        shared_ptr<AC> abby(new AC());
        shared_ptr<TY> taeyeon(new TY());

        abby->setgf(taeyeon);
        
        taeyeon->setbf(abby);

        if(!abby->over())
                sleep(1);

        return 0;
}
